/// null = 未请求，1 = 已允许，0 = 拒绝|受限, 2 = 系统未开启

var isIOS
const IosAndroidPermType = [
  {
    key: 'album',
    ios: 'album',
    android: 'android.permission.READ_EXTERNAL_STORAGE',
    title: '相册权限申请说明',
    content: `${Env.GlobAppTitle}正在申请手机相册权限，用于从本地相册选择图片、视频或者文件等场景`,
  },
  {
    key: 'camera',
    ios: 'camera',
    android: 'android.permission.CAMERA',
    title: '相机权限申请说明',
    content: `${Env.GlobAppTitle}正在申请手机相机权限，用于使用相机拍摄照片、录制视频等场景`,
  },
  {
    key: 'location',
    ios: 'location',
    android: 'android.permission.ACCESS_FINE_LOCATION',
    title: '定位权限申请说明',
    content: `${Env.GlobAppTitle}正在申请手机定位权限，用于获取用户附近的房源信息`,
  },
  { key: 'call', ios: 'call', android: 'android.permission.CALL_PHONE', title: '打电话权限申请说明', content: `${Env.GlobAppTitle}正在申请手机打电话权限，用于与商家沟通房源信息` },
  { key: 'push', ios: 'push', android: 'android.permission.ACCESS_NETWORK_STATE', title: '推送', content: '' },
  { key: 'contact', ios: 'contact', android: 'android.permission.READ_CONTACTS', title: '通讯录', content: '' },
  {
    key: 'record',
    ios: 'record',
    android: 'android.permission.RECORD_AUDIO',
    title: '访问麦克风',
    content: `${Env.GlobAppTitle}正在申请访问手机麦克风,用于预定、签约合同时的活体识别功能`,
  },
]
let permDialogView = null
let permissionListener = null

const IOSPermFuns = {
  album: () => {
    const PHPhotoLibrary = plus.ios.import('PHPhotoLibrary')
    const authStatus = PHPhotoLibrary.authorizationStatus()
    plus.ios.deleteObject(PHPhotoLibrary)
    return authStatus === 0 ? null : authStatus === 3 ? 1 : 0
  },
  camera: () => {
    const AVCaptureDevice = plus.ios.import('AVCaptureDevice')
    const authStatus = AVCaptureDevice.authorizationStatusForMediaType('vide')
    plus.ios.deleteObject(AVCaptureDevice)
    return authStatus === 0 ? null : authStatus === 3 ? 1 : 0
  },
  location: () => {
    const cllocationManger = plus.ios.import('CLLocationManager')
    const enable = cllocationManger.locationServicesEnabled()
    const status = cllocationManger.authorizationStatus()
    plus.ios.deleteObject(cllocationManger)
    if (!enable) return 2
    return status === 0 ? null : status === 3 || status === 4 ? 1 : 0
  },
  push: () => {
    const UIApplication = plus.ios.import('UIApplication')
    const app = UIApplication.sharedApplication()
    let result = 0
    if (app.currentUserNotificationSettings) {
      const settings = app.currentUserNotificationSettings()
      const enabledTypes = settings.plusGetAttribute('types')
      result = enabledTypes === 0 ? 0 : 1
      plus.ios.deleteObject(settings)
    } else {
      const enabledTypes = app.enabledRemoteNotificationTypes()
      result = enabledTypes === 0 ? 3 : 4
    }
    plus.ios.deleteObject(app)
    plus.ios.deleteObject(UIApplication)
    return result
  },
  contact: () => {
    const CNContactStore = plus.ios.import('CNContactStore')
    const cnAuthStatus = CNContactStore.authorizationStatusForEntityType(0)
    plus.ios.deleteObject(CNContactStore)
    return cnAuthStatus === 0 ? null : cnAuthStatus === 3 ? 1 : 0
  },
  record: () => {
    const avaudiosession = plus.ios.import('AVAudioSession')
    const avaudio = avaudiosession.sharedInstance()
    const status = avaudio.recordPermission()
    plus.ios.deleteObject(avaudiosession)
    return status === 1970168948 ? null : status === 1735552628 ? 1 : 0
  },
  calendar: () => {
    const EKEventStore = plus.ios.import('EKEventStore')
    const ekAuthStatus = EKEventStore.authorizationStatusForEntityType(0)
    plus.ios.deleteObject(EKEventStore)
    return ekAuthStatus === 3 ? 1 : null
  },
  memo: () => {
    const EKEventStore = plus.ios.import('EKEventStore')
    const ekAuthStatus = EKEventStore.authorizationStatusForEntityType(1)
    plus.ios.deleteObject(EKEventStore)
    return ekAuthStatus === 3 ? 1 : null
  },
  call: () => {
    return 1
  },
}

function requestIOS(permissionID) {
  return new Promise((resolve) => {
    resolve(IOSPermFuns[permissionID] ? IOSPermFuns[permissionID]() : 0)
  })
}

function requestAndroid(permissionID) {
  return new Promise((resolve) => {
    plus.android.requestPermissions(
      [permissionID],
      (resultObj) => {
        let result = 0
        if (resultObj.granted.length > 0) result = 1
        if (resultObj.deniedPresent.length > 0) result = 0
        if (resultObj.deniedAlways.length > 0) result = -1
        resolve(result)
      },
      (error) => {
        resolve({ code: error.code, message: error.message })
      },
    )
  })
}

function gotoAppPermissionSetting() {
  if (permission.isIOS) {
    const UIApplication = plus.ios.import('UIApplication')
    const application2 = UIApplication.sharedApplication()
    const NSURL2 = plus.ios.import('NSURL')
    const setting2 = NSURL2.URLWithString('app-settings:')
    application2.openURL(setting2)
    plus.ios.deleteObject(setting2)
    plus.ios.deleteObject(NSURL2)
    plus.ios.deleteObject(application2)
  } else {
    const Intent = plus.android.importClass('android.content.Intent')
    const Settings = plus.android.importClass('android.provider.Settings')
    const Uri = plus.android.importClass('android.net.Uri')
    const mainActivity = plus.android.runtimeMainActivity()
    const intent = new Intent()
    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
    const uri = Uri.fromParts('package', mainActivity.getPackageName(), null)
    intent.setData(uri)
    mainActivity.startActivity(intent)
  }
}

function checkPermission(key) {
  return new Promise(async (resolve, reject) => {
    const permobj = IosAndroidPermType.find((item) => item.key === key)
    if (!permobj) {
      throw new Error('没有匹配到的权限，请自行配置‘IosAndroidPermType’')
    }

    if (!permission.isIOS) {
      requestPermissionDialog(permobj)
    }

    let status = permission.isIOS ? await requestIOS(permobj.ios) : await requestAndroid(permobj.android)

    if (status === null || status === 1) {
      status = 1
    } else if (status === 2) {
      uni.showModal({
        content: `系统${permobj.title}已关闭`,
        confirmText: '确定',
        showCancel: false,
      })
    } else if (status.code) {
      uni.showModal({
        content: status.message,
      })
    } else {
      uni.showModal({
        content: `需要${permobj.title}权限`,
        confirmText: '设置',
        success: (res) => {
          if (res.confirm) {
            gotoAppPermissionSetting()
          }
        },
      })
    }
    resolve(status)
  })
}

function requestPermissionDialog(permObj) {
  try {
    if (!permissionListener) {
      permissionListener = uni.createRequestPermissionListener()
    }

    permissionListener.onConfirm((res) => {
      setPermDialog({ permObj, status: true, permArr: res })
    })
    permissionListener.onComplete((res) => {
      setPermDialog({ permObj: {}, status: false, permArr: res })
    })
  } catch (err) {
    console.log('监听弹框错误', err)
  }
}

function setPermDialog({ permObj, status, permArr }) {
  try {
    if (permObj && !permArr.includes(permObj.android)) return permDialogView && permDialogView.close()
    if (!status) return permDialogView && permDialogView.close()
    const systemInfo = uni.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight
    const navigationBarHeight = systemInfo.platform === 'android' ? 48 : 44
    const totalHeight = statusBarHeight + navigationBarHeight
    permDialogView = new plus.nativeObj.View('per-modal', {
      top: '0px',
      left: '0px',
      width: '100%',
      backgroundColor: '#444',
    })
    permDialogView.drawRect({ color: '#fff', radius: '5px' }, { top: `${totalHeight}px`, left: '5%', width: '90%', height: '100px' })
    permDialogView.drawText(permObj.title, { top: `${totalHeight + 5}px`, left: '8%', height: '30px' }, { align: 'left', color: '#000' })
    permDialogView.drawText(
      permObj.content,
      { top: `${totalHeight + 35}px`, height: '60px', left: '8%', width: '84%' },
      { whiteSpace: 'normal', size: '14px', align: 'left', color: '#656563' },
    )
    permDialogView.show()
  } catch (e) {
    console.log(e, '权限说明弹框样式错误')
  }
}

const permission = {
  get isIOS() {
    return typeof isIOS === 'boolean' ? isIOS : (isIOS = uni.getSystemInfoSync().platform === 'ios')
  },
  requestIOS,
  requestAndroid,
  gotoAppSetting: gotoAppPermissionSetting,
  checkPermission,
}

export default permission
